
<template>
  <div>
    <el-row>
      <el-col :span="6" class="myLeftDiv">
        <div class="myTree">
          <div style="padding-bottom: 10px;">
            <span class="myTitle">成员类型</span>
          </div>
          <div class="tree-detail">
            <el-tree
              :data="treeData"
              :props="defaultProps"
              @current-change="handleTreeCurrentChange"
              :default-expanded-keys="defaultExpandedKeys"
              :highlight-current="true"
              node-key="id"
              class="nodes-tree"
              :expand-on-click-node="false">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ data.name }}（{{ memberTypeCount[data.id] }}）</span>
              </span>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="18" class="myRightDiv">
        <div style="padding-bottom: 10px;">
          <el-row>
            <el-col :span="16">
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="addRecord">添加</el-button>
              <el-button type="primary" size="mini" icon="el-icon-delete" @click="deleteRecordByBatch">批量刪除</el-button>
            </el-col>
            <el-col :span="8">
                <el-input placeholder="搜索成员" @keyup.enter.native="fetchData" prefix-icon="el-icon-search" size="small" v-model="queryCondition.memberName"></el-input>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-table
            ref="singleTable"
            :data="tableData"
            tooltip-effect="dark"
            @row-contextmenu="rowContextmenu"
            @cell-dblclick="cellClick"
            @row-click="rowClick"
            @sort-change="sortChange"
            @current-change="handleCurrentChange"
            @selection-change="handleSelectionChange"
            highlight-current-row
            height="400"
            style="width: 100%">
            <el-table-column :selectable="dataSelectable" align="center" type="selection" width="40"></el-table-column>
            <el-table-column width="50" align="center" label="序号">
              <template slot-scope="scope">
                <span>{{scope.$index + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column width="150" prop="memberName" align="center" label="成员名称">
              <template slot-scope="scope">
                <span v-if="scope.row.isNow != 1" class="myInheritSpan" title="该成员继承自父级分组，如需删除该成员请在分组人员权限中操作。">继承</span>
                {{scope.row.memberName}}
              </template>
            </el-table-column>
            <el-table-column width="120" prop="memberType" align="center" label="成员类型">
              <template slot-scope="scope">
                <el-select :disabled="scope.row.isNow != 1" v-model="scope.row.memberType" size="mini" @change="memberTypeChangeHandler(scope.row)">
                  <el-option
                    v-for="item in memberTypeOptions"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column width="150" prop="projectGroupName" align="left"  :show-overflow-tooltip="showOverflowTooltip" label="继承分组"></el-table-column>
            <el-table-column align="center" label="操 作">
              <template slot-scope="scope">
                <el-button v-if="scope.row.isNow == 1" type="text" @click.native.stop="deleteRecord(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <el-dialog v-if="dialogVisibleUser" custom-class="dhcWebLayer" top="30px" :close-on-click-modal="false"
               :destroy-on-close="true"  title="设置项目成员" :visible.sync="dialogVisibleUser" width="60%" :append-to-body="true">
      <member-select :componentCustomProps="subComponentCustomProps" @closeComponent="closeComponent"></member-select>
    </el-dialog>
  </div>
</template>

<script>
  import paging from '@/components/demoAssembly/paging' // 分页
  import memberSelect from './memberSelect'
  import {
    selectGroupMemberList,
    insertGroupMemberByBatch,
    updateGroupMember,
    deleteForceGroupMemberByBatch
  } from '@/api/apiModel/apiMember.js'

  export default {
    name: 'groupMemberCom',
    data() {
      return {
        defaultExpandedKeys: [],
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        pageSizes: [10, 20, 30, 40],
        // 分页参数
        pagingArgs: {
          currentPageNo: 1,
          totalCount: 0
        },
        showOverflowTooltip: true,
        tableData: [], // 列表数据
        queryArgs: {
          sort: [
            // {
            //   property: 'procCategoryName',
            //   direction: 'ASC'
            // },
            // {
            //   property: 'procName',
            //   direction: 'ASC'
            // }
          ]
          // rowBounds: {
          //   offset: 0,
          //   limit: 10
          // }
        }, // 查询参数
        queryCondition: {
          memberType: '',
          memberName: ''
        },
        memberTypeOptions: [
          {
            key: '0',
            value: '管理成员'
          },
          {
            key: '-1',
            value: '读写成员'
          },
          {
            key: '-2',
            value: '只读成员'
          }
        ],
        memberTypeCount: {
          '': 0,
          '0': 0,
          '-1': 0,
          '-2': 0
        },
        groupId: '',
        groupName: '',
        checkRecord: [],
        dialogVisibleUser: false,
        subComponentCustomProps: {}
      }
    },
    props: ['componentCustomProps'],
    watch: {
      //
    },
    computed: {

    },
    filters: {

    },
    components: {
      paging,
      memberSelect
    },
    /**
     * 组件创建完成后，查询列表数据
     */
    created() {
    },
    mounted() {
      this.groupId = this.componentCustomProps.groupId
      this.groupName = this.componentCustomProps.groupName
      this.getMemberTypeData()
      this.fetchData()
    },
    methods: {
      handleTreeCurrentChange(data, node) {
        //
        this.queryCondition.memberType = data.id
        this.fetchData()
      },
      getMemberTypeData() {
        this.fetchDataAll()
        this.treeData = [
          {
            id: '',
            name: '所有成员',
            count: this.memberTypeCount['****']
          },
          {
            id: '0',
            name: '管理成员',
            count: this.memberTypeCount['0']
          },
          {
            id: '-1',
            name: '读写成员',
            count: this.memberTypeCount['-1']
          },
          {
            id: '-2',
            name: '只读成员',
            count: this.memberTypeCount['-2']
          }
        ]
      },
      rowClick() {
        // 行单击事件
      },
      cellClick(row, column, cell, event) {
        // 列单击事件
      },
      rowContextmenu(row, column, e) {
        // 右键菜单
        window.event.returnValue = false
      },
      pageSizeChange(val) {
        this.queryArgs.rowBounds.limit = val
        this.queryArgs.rowBounds.offset = 0
        this.pagingArgs.currentPageNo = 1
        this.fetchData()
      },
      sortChange(col) {
        //
        if (col.prop) {
          let tempDirection = 'ASC'
          if (col.order === 'descending') {
            tempDirection = 'DESC'
          }
          const sort = {
            property: col.prop,
            direction: tempDirection
          }
          this.queryArgs.sort = []
          this.queryArgs.sort.push(sort)
          this.fetchData()
        }
      },
      pagingQuery(val) { // 分页
        this.queryArgs.rowBounds.offset = (val - 1) * this.queryArgs.rowBounds.limit
        this.pagingArgs.currentPageNo = val
        this.fetchData()
      },
      buildQueryConditions() {
        let tempQueryCondition = []

        for (let key in this.queryCondition) {
          let queryValue = this.queryCondition[key]
          if (queryValue != null && queryValue !== '') {
            let queryProperty = key
            let type = 'LIKE'
            if (key === 'memberType') {
              type = 'EQ'
            }
            tempQueryCondition.push({
              property: queryProperty,
              type: type,
              value: queryValue
            })
          }
        }

        return tempQueryCondition
      },
      dataSelectable(row, index) {
        return (row.isNow === 1)
      },
      fetchData() { // 获取内容
        this.queryArgs.condition = this.buildQueryConditions()
        selectGroupMemberList(this.queryArgs, this.groupId).then(res => {
          // console.log(res.data)
          let tempData = res.data.data
          if (tempData) {
            this.tableData = tempData.records
          }
        })
      },
      fetchDataAll() { // 获取内容
        this.memberTypeCount = {
          '': 0,
          '0': 0,
          '-1': 0,
          '-2': 0
        }
        selectGroupMemberList({}, this.groupId).then(res => {
          // console.log(res.data)
          let tempData = res.data.data
          if (tempData) {
            if (tempData.records && tempData.records.length > 0) {
              tempData.records.forEach((item, index) => {
                if (item) {
                  this.memberTypeCount[item.memberType] = this.memberTypeCount[item.memberType] + 1
                }
              })
              this.memberTypeCount[''] = tempData.records.length
            }
          }
        })
      },
      timeFormat(time) {
        let tempDate = time
        try {
          if (time && time.length > 8) {
            tempDate = time.substring(0, 4) + '-' + time.substring(4, 6) + '-' + time.substring(6, 8)
            tempDate = tempDate + ' ' + time.substring(8, 10) + ':' + time.substring(10, 12) + ':' + time.substring(12, 14)
          }
        } catch (e) {
          //
          console.info(e)
        }
        return tempDate
      },
      handleCurrentChange(currentRow, oldCurrentRow) {
        //
        // this.selectRecord = currentRow
      },
      handleSelectionChange(selection) {
        this.checkRecord = selection
      },
      memberTypeChangeHandler(record) {
        let updataRecord = {
          memberType: record.memberType
        }
        updateGroupMember(updataRecord, record.id).then(res => {
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
          } else {
            this.$message({
              type: 'error',
              message: '操作失败！'
            })
          }
          this.fetchData()
        })
      },
      addRecord() {
        //
        let existMemberIds = []
        if (this.tableData && this.tableData.length > 0) {
          this.tableData.forEach((item, index) => {
            if (item && item.isNow === 1) {
              existMemberIds.push(item.memberId)
            }
          })
        }
        this.subComponentCustomProps = {
          existMemberIds: existMemberIds
        }
        this.dialogVisibleUser = true
      },
      deleteRecord(record) {
        this.$confirm('是否删除，请谨慎操作！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          ids.push(record.id)
          this.deleteMember({
            ids: ids
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消刪除'
          })
        })
      },
      deleteRecordByBatch() {
        if (this.checkRecord && this.checkRecord.length <= 0) {
          this.$message({
            type: 'warning',
            message: '请选择成员！'
          })
          return
        }
        this.$confirm('是否删除，请谨慎操作！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          this.checkRecord.forEach((item, index) => {
            if (item) {
              ids.push(item.id)
            }
          })
          this.deleteMember({
            ids: ids
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消刪除'
          })
        })
      },
      deleteMember(args) {
        deleteForceGroupMemberByBatch(args).then(res => {
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
            this.fetchData()
            this.fetchDataAll()
          } else {
            this.$message({
              type: 'error',
              message: '操作失败！'
            })
          }
        })
      },
      closePage() {
        this.$emit('closeDialog')
      },
      closeComponent(type, args) {
        if (type === 'save' && args) {
          let insertArgs = []

          let memberType = args.memberType
          let memberUserList = args.memberUserList

          if (memberUserList && memberUserList.length > 0){
            memberUserList.forEach((item, index) => {
              if (item) {
                insertArgs.push({
                  projectGroupId: this.groupId,
                  memberType: memberType,
                  memberId: item.userId,
                  memberName: item.userName
                })
              }
            })
          }

          insertGroupMemberByBatch(insertArgs).then(res => {
            if (res.data.success) {
              this.$message({
                type: 'success',
                message: '操作成功！'
              })
              this.dialogVisibleUser = false
              this.fetchData()
              this.fetchDataAll()
            } else {
              this.$message({
                type: 'error',
                message: '操作失败！'
              })
            }
          })
          // this.record.toUserId = args.userId
          // this.record.toUserName = args.userName
        } else if (type === 'clear') {
          // this.record.toUserId = ''
          // this.record.toUserName = ''
          this.dialogVisibleUser = false
        } else {
          this.dialogVisibleUser = false
        }
      }
    }
  }
</script>
<style scoped>
  .myLeftDiv{
    height: 100%;
    border-right: 1px solid #ccc;
  }
  .myRightDiv{
    padding-left: 3px;
  }
  .myTitle {
    border-left: 4px solid #064475;
    color: #000;
    padding-left: 16px;
    line-height: 26px;
    margin-top: 0;
    font-size: 14px;
    display: inline-block;
    vertical-align: middle;
    font-weight: 700;
  }
  .myTree{
    height: 440px;
  }
  .tree-detail{
    border-top: 1px solid #ccc;
    overflow-y: auto;
  }
  .myInheritSpan{
    display: inline-block;
    width: 40px;
    line-height: 22px;
    text-align: center;
    background-color: #8b8b8b;
    color: white;
    margin-right: 5px;
    border-radius: 3px;
  }
</style>
